package com.msh.platform.elm.controller;

import com.msh.platform.bizmedia.base.conf.ResponseResult;
import com.msh.platform.elm.common.constants.Constants;
import com.msh.platform.elm.common.util.SortUtils;
import com.msh.platform.elm.vo.TokenVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

import javax.validation.Valid;

/**
 * @Author zhangyangsong
 * @Description :
 * @Date: Created in 2018/11/8
 * @Copyright: ©2018 all rights reserved.
 */
@RestController
@RequestMapping(value = "/common")
@Api(tags = "公共接口")
@Slf4j
public class CommonController extends BaseController{

    @Autowired
    private RedisTemplate redisTemplate;
    
    @ApiOperation(value = "退出")
    @PostMapping(path = "/logout")
    public ResponseResult logout(@RequestBody @Valid TokenVO paramVo, BindingResult errors) {
    	if (errors.hasErrors()){  //参数校验失败
			//返回参数校验错误信息
    		return ResponseResult.fail(Constants.RESP_FAIL, errors.getAllErrors().get(0).getDefaultMessage());
	    }
    	//校验sign字符串
    	Map<String, Object> signMap = new HashMap<String, Object>();
		signMap.put("token", paramVo.getToken());
		String paramStr = SortUtils.sortMap(signMap);
		boolean flag = validateSign(paramStr, paramVo.getSign());
		log.info("验证签名结果：" + flag);
		if(flag){
			Object userObj = getUserByToken(paramVo.getToken());
			if(userObj!=null) {
		    	if(redisTemplate.hasKey(paramVo.getToken())) {
		    		redisTemplate.delete(paramVo.getToken());  //删除token
		    	}
		    	return ResponseResult.success(null);
			}else {
				return ResponseResult.fail(Constants.RESP_TOKEN_TIMEOUT, "未登录或登录超时");
			}
		}else {
			return ResponseResult.fail(Constants.RESP_FAIL, "签名校验失败");
		}
    }
    
}
